/* 
 * Copyright (c) 2021, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.boot.support.jackson;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.cory.boot.domain.bean.Result;
import com.cory.boot.support.jackson.annotation.JSON;
import com.cory.boot.support.jackson.annotation.JSONS;

/**
 * @author xiongcong
 * @date 2021-06-08
 */
@Aspect
@Component
public class JsonReturnAspect {
    
    @Pointcut("@annotation(com.cory.boot.support.jackson.annotation.JSON) || @annotation(com.cory.boot.support.jackson.annotation.JSONS)")
    public void jsonReturnAspect(){}

    //Around注解改变服务的返回值
    //统一返回值使用R工具类,所以返回结果都是在R的data属性中
    @Around("jsonReturnAspect()")
    public Result<?> around(ProceedingJoinPoint pjp) throws Throwable {
        Result<?> result = (Result<?>)pjp.proceed();
        Object data = result.getData();
        
        MethodSignature methodSignature =  (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();
        
        Annotation[] annos = method.getAnnotations();
        
        CustomerJsonSerializer jsonSerializer = new CustomerJsonSerializer();
        
        Arrays.asList(annos).forEach(a -> { // 解析注解，设置过滤条件
            if (a instanceof JSON) {
                JSON json = (JSON) a;
                jsonSerializer.filter(json);
            } else if (a instanceof JSONS) { // 使用多重注解时，实际返回的是 @Repeatable(JSONS.class) 内指定的 @JSONS 注解
                JSONS jsons = (JSONS) a;
                Arrays.asList(jsons.value()).forEach(json -> {
                    jsonSerializer.filter(json);
                });
            }
        });
        
        if (data != null) {
            String json = jsonSerializer.toJsonString(data);
            return Result.custom(result.getCode(), result.getMsg(), JSONObject.parseObject(json));
        }
        
//        FieldFilterSerializer fieldFilter = new FieldFilterSerializer();
//        
//        //这里传入公共类 由于所有类都继承了mybatis的公共字段类BaseModel
//         //所以只要传入BaseModel就可以进行全部类的过滤
//        fieldFilter.filter(BaseModel.class, annotation.include(), annotation.exclude());
//        //返回过滤后的json字符串
//        String jsonString = fieldFilter.toJSONString(r.getData());
//        //将返回的json字符串转换成 JSONObject 或者 JSONArray并放入到R的data属性中返回到前端
////        r.setData(JSON.parseObject(jsonString, annotation.classez()));
        return result;
    }
}
